const app = getApp()
const globalUrl = app.globalData.globalUrl
const img = app.globalData.img

//计时器
var timeOut
var closestInterval

//websocket
var socketOpen = false
var socketMsgQueue = []

var distanceArray          //排完序后的socketData
var totalSeats             //总座位数

var itemChoose = false             //判断是否点击列表的item
var latitude
var longitude

var cars = []
var seats = []

var SocketTask    //websocket 任务
Page({
  data: {
    current: 0,
    img: img,
    map: false,
    avata: app.globalData.avata,
    // isShowBottom: true,
    flag: -1,
    animationData: {},
    isFixed: false,
    isBookFixed: false,
    checkBook: false,   //判断状态蒙屏
    // stop: false,
    // isTouch: false,     
    isBook: false,        //是否已预约
    isPayed: false,      //是否支付

    cars,
    car: ' ',
    seats,
    seat: '01',


    //站点
    // stores: [
    //   '游泳场站',
    //   '海宇站',
    //   '海妙站',
    //   '海宁站',
    //   '科技楼',
    //   '钟海楼',
    //   '第二教学楼',
    //   '第三饭堂',
    //   '海沁',
    //   '海怡',
    //   '第四饭堂',
    //   '海乐',
    //   '校门口',
    //   '主楼',
    //   '图书馆',
    // ],
    // store: '游泳场站',

    mapCtx: null,
    longitude: 110.3002613783,
    latitude: 21.1527713471,

    //socket
    socketData: {},
    markers: [
      {
        iconPath: '../../../images/home/01.png',
        id: 1,
        latitude: 21.1477432749,
        longitude: 110.3043115139,
        rotate: 0,
        width: 40,
        height: 40
      },
      {
        iconPath: '../../../images/home/02.png',
        id: 2,
        latitude: 21.1484437131,
        longitude: 110.3043115139,
        rotate: 0,
        width: 40,
        height: 40
      },
      {
        iconPath: '../../../images/home/03.png',
        id: 3,
        latitude: 21.1503699011,
        longitude: 110.3050035238,
        rotate: 0,
        width: 40,
        height: 40
      },
      {
        iconPath: '../../../images/home/04.png',
        id: 4,
        latitude: 21.1511453723,
        longitude: 110.3039842844,
        rotate: 0,
        width: 40,
        height: 40
      },
      {
        iconPath: '../../../images/home/05.png',
        id: 5,
        latitude: 21.1518357884,
        longitude: 110.3019136190,
        rotate: 0,
        width: 40,
        height: 40
      },
      {
        iconPath: '../../../images/home/06.png',
        id: 6,
        latitude: 21.1512404298,
        longitude: 110.3005671501,
        rotate: 0,
        width: 40,
        height: 40
      },
      {
        iconPath: '../../../images/home/07.png',
        id: 7,
        latitude: 21.1508752086,
        longitude: 110.2988129854,
        rotate: 0,
        width: 40,
        height: 40
      },
      {
        iconPath: '../../../images/home/08.png',
        id: 8,
        latitude: 21.1528213768,
        longitude: 110.3002452850,
        rotate: 0,
        width: 40,
        height: 40
      },
      {
        iconPath: '../../../images/home/09.png',
        id: 9,
        latitude: 21.1547625166,
        longitude: 110.3006368876,
        rotate: 0,
        width: 40,
        height: 40
      },
      //--------------------------
      {
        iconPath: '../../../images/home/10.png',
        id: 10,
        latitude: 21.1535968352,
        longitude: 110.2968227863,
        rotate: 0,
        width: 40,
        height: 40
      },
      {
        iconPath: '../../../images/home/11.png',
        id: 11,
        latitude: 21.1549726384,
        longitude: 110.2957981825,
        rotate: 0,
        width: 40,
        height: 40
      },
      {
        iconPath: '../../../images/home/12.png',
        id: 12,
        latitude: 21.1573189788,
        longitude: 110.2960288525,
        rotate: 0,
        width: 40,
        height: 40
      },
      {
        iconPath: '../../../images/home/13.png',
        id: 13,
        latitude: 21.1456569501,
        longitude: 110.3019887209,
        rotate: 0,
        width: 40,
        height: 40
      },
      {
        iconPath: '../../../images/home/14.png',
        id: 14,
        latitude: 21.1487889279,
        longitude: 110.3014415503,
        rotate: 0,
        width: 40,
        height: 40
      },
      {
        iconPath: '../../../images/home/15.png',
        id: 15,
        latitude: 21.1499046164,
        longitude: 110.3031527996,
        rotate: 0,
        width: 40,
        height: 40
      },
    ],
    includepoints: [{
      latitude: 21.15112,
      longitude: 110.3009,
    }],
  },
  onShow(){
    var count = 0
    this.getConnect()
    //连接失败
    wx.onSocketError(res => {
      count ++
      socketOpen = false
      this.getConnect()
      if (!socketOpen && count > 1){
        console.log("断了")
        wx.showLoading({
          mask: true
        })
      }
    })
  },
  getConnect() {
    var userId = app.globalData.userId
    if (!userId) {                    //userId为空
      this.getConnect()
      return;
    }
    //------------------------websocket 获取车辆的位置
    var that = this
    wx.connectSocket({
      url: 'wss://www.bjhweb.xyz/gdouBus/websocket/passenger/' + userId
      // url: 'wss://wteam.linpr.cn/gdouBus/websocket/passenger/' + app.globalData.userId
    })

    wx.onSocketOpen(function (res) {
      console.log("打开websocket")
      socketOpen = true
      // for (let i = 0; i < socketMsgQueue.length; i++) {
      //   sendSocketMessage(socketMsgQueue[i])
      // }
      // socketMsgQueue = []
      wx.hideLoading()
    })

    function sendSocketMessage(msg) {
      if (socketOpen) {
        wx.sendSocketMessage({
          data: msg
        })
      } else {
        socketMsgQueue.push(msg)
      }
    }
    wx.onSocketMessage(function (res) {
      var data
      try{
        data = JSON.parse(res.data)
      }catch(e){
        console.log(e)
      }
      var oldmarkers = that.data.markers
      //储存socketData
      var socketData = data
      var newmarkers = [];
      var j = 15;
      for (let i in data) {
        j++
        var id = data[i].carId
        if (id< 10){
          id = '0' + id
        }
        var markerItem = {
          iconPath: '../../../images/car/' + id+'.png',
          id: j,
          latitude: data[i].lat,
          longitude: data[i].lon,
          rotate: 0,
          width: 46,
          height: 46
        }
        newmarkers.push(markerItem)
      }
      newmarkers = oldmarkers.concat(newmarkers)
      that.setData({
        socketData,
        newmarkers: newmarkers
      })
    })
    //----------------------计算 离我最近
    closestInterval = setInterval(()=>{
      this.getClosest()
    },2000)
    // setTimeout(() =>{
    //   this.getClosest()
    //   setTimeout(arguments.callee, 2000);
    // }, 2000);
  },
  // isEmptyObject(e) {
  //     //对象是否为空；判断是否是第一次授权，非第一次授权且授权失败则进行提醒
  //     var t;
  //     for(t in e)
  //     return !1;
  //     return !0
  // },
  onLoad() {
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#3aadfe',
      animation: {
        duration: 0,
        timingFunc: 'linear'
      }
    })
    wx.showModal({
      title: '温馨提示',
      content: '本周环校车办公室（校门口环校车卡充值处）值班时间为每天的 17:00-19:00， 请还没有办理小程序余额转入登记的同学在上班时间到点办理登记录入。',
      showCancel: false,
    })
    this.setData({
      avata: app.globalData.avata,
    })
    wx.getStorage({
      key: 'isFirst',
      success: res=> {
        this.setData({isFirst: false})
      },
      fail: res => {
        this.setData({isFirst: true, tips: 1})
        wx.setStorage({
          key: 'isFirst',
          data: 2,
        })
      }
    })
    wx.showShareMenu({
      withShareTicket: true
    })
    //------------------------------------------------------
    this.getLocation();
    // -----------------------------
    wx.request({
      url: globalUrl + 'isLogin',
      header: app.globalData.header,
      method: 'POST',
      success: res => {
        if (!res.data.resultParm.isLogin) {   //登录过时
          // wx.request({
          //   url: '',
          // })
        }
      }
    })
  },
  onUnload() {
    // clearInterval(interval)
    clearInterval(closestInterval)
    // SocketTask.close()
    // SocketTask.onClose(function (res) {
    //   console.log("已关闭websocket")
    // })
    wx.closeSocket()
    wx.onSocketClose(function (res) {
      console.log("已关闭websocket")
    })
  },
  //隐藏
  onHide(){
    clearInterval(closestInterval)
    wx.closeSocket()
    wx.onSocketClose(function (res) {
      console.log("已关闭websocket")
    })
  },
  getLocation(){
    wx.getLocation({
      type: 'gcj02',  //wgs84  //
      success: res=> {
        latitude = res.latitude
        longitude = res.longitude
        this.setData({
          latitude,
          longitude,
        })
      },
      fail: res=>{
        console.log("fail")
        this.checkAuthor()
      }
    })
  },
  checkAuthor(){
    //-------------------------------------检测地理位置授权状态
    wx.getSetting({
      success: res => {
        if (!res.authSetting['scope.userLocation']) {
          // wx.authorize({
          //   scope: 'scope.userLocation',
          //   success(res) {
          //     // console.log(res)
          //   }
          // })
          wx.showModal({
            title: '未授权',
            content: '请在小程序设置界面中打开“位置信息”授权状态,否则将严重影响该小程序的使用。',
            showCancel: false,
            success: res=> {
              if (res.confirm) {
                // console.log('用户点击确定')
                wx.openSetting({
                  success: res => {
                    // wx.showModal({
                    //   title: "提示",
                    //   content: '建议重新打开小程序，以获取你的位置信息',
                    //   showCancel: false
                    // })
                    this.getLocation()
                  }
                })
              }
            }
          })
        }
      }
    })
  },
  //--------------------------离我最近
  getClosest(){
    distanceArray = []   //排完序后的socketData
    var socketData = this.data.socketData
    // try{
    //   // var string = JSON.stringify(this.data.socketData)
    //   socketData = JSON.parse(this.data.socketData)
    // }catch(e){
    //   console.log(e)
    // }
    for (let i in socketData) { 
      distanceArray.push(socketData[i])
    }
    function compare(carLatitude, carlongitude){
      return function(a,b){
        var value1 = (longitude - a[carlongitude]) * (longitude - a[carlongitude]) + (latitude - a[carLatitude]) * (latitude - a[carLatitude])
        var value2 = (longitude - b[carlongitude]) * (longitude - b[carlongitude]) + (latitude - b[carLatitude]) * (latitude - b[carLatitude])
        return value1 - value2
      }
    }
    distanceArray = distanceArray.sort(compare('lat', 'lon')) //按照距离重新排序
    if(distanceArray.length == 1 ){
      this.setData({
        closestCar: distanceArray[0],               //离我最近
        restCars: []
      })
    }else
    if (distanceArray.length > 1){
      this.setData({
        closestCar: distanceArray[0],     
        restCars: distanceArray.slice(1)           //其余车辆
      })
    }
    this.setData({
      distanceArray
    })
  },
  navigateToMy() {
    wx.showLoading({
      mask: true
    })
    wx.navigateTo({
      url: '../balance/balance',
    })
  },
  //选择车辆
  bindChange(e) {
    var val = e.detail.value
    if (!itemChoose){
      totalSeats = distanceArray[val[0]].tolalNumber      
      var seats = []
      for (let i = 1; i <= totalSeats; i++) {
        if (i < 10) {
          i = "0" + i;
        }
        seats.push(i)
      }
      this.setData({seats})
    }
    var n = this.data.seats[val[1]]
    if(n == undefined){
      n = 16
    }
    this.setData({
      car: this.data.cars[val[0]],
      seat: n,
      can: true
    })
  },
  bindpickstart(e){
    this.setData({ can: false })
    // console.log(e)
  },
  bindpickend(e){
    this.setData({ can: true})
  },

  //取消蒙层
  nofix(){
    this.setData({
      isFixed: false,
      isBookFixed: false,
      checkBook: false
    })
  },
  //去支付
  pay(){
    if(this.data.can==false)
      return
    var seat = parseInt(this.data.seat)
    wx.showModal({
      title: '支付',
      content: this.data.car + '号车,' + seat + '号座',
      success: res => {
        if (res.confirm) {
          var column
          var row
          distanceArray.forEach(item => {
            if (item.carId == this.data.car) {
              totalSeats = item.tolalNumber
            }
          })
    if (totalSeats == 17){                    //17座车
      column = (seat+2) % 4;
      row = parseInt((seat+2)/4);
    }
    if (totalSeats == 22) {                  //22座车
      column = (seat+1) % 4;
      row = parseInt((seat+1)/4);
    }
    // console.log(totalSeats)
    // console.log(column)
    // console.log(row)
    this.setData({
      isFixed: false
    })
    // 发送支付请求
    wx.showLoading({
      title: '请求中...',
      mask: true
    })
    wx.request({
      url: globalUrl + 'passenger/payOnBus',
      header: app.globalData.header,
      method: 'POST',
      data: {
        "carId": parseInt(this.data.car),
        "column": column,
        "row": row
      },
      success: res =>{   
        wx.hideLoading()   
        if(res.data.serviceResult == "1"){
          this.setData({
            isPayed: true,
            isBook: false,
            payedCar: this.data.car,
            payedSeat: seat
          })

          wx.showToast({
            title: '支付成功',
          })
        }else {
          wx.showToast({
            title: res.data.resultInfo,
            image: '/dingdang/images/icon/warn.png'
          })
        }
        var timeout = setTimeout(() =>{
          this.setData({isPayed: false})
        },2000)
      }
    })
    }
    }
    })
  },
  //点击车辆列表选择车辆
  chooseCarPay(e){
    itemChoose = true               //点击列表的
    var carItem = e.currentTarget.dataset.car
    var certainCarId = []
    certainCarId.push(carItem.carId)
    // if (certainCarId[0] < 10){
    //   certainCarId[0] = "0" + certainCarId
    // }

    var certainCar_seats = []
    for (let i = 1; i <= carItem.tolalNumber; i++) {
      if (i < 10) {
        i = "0" + i;
      }
      certainCar_seats.push(i)
    }
    this.setData({
      car: certainCarId,
      cars: certainCarId,
      seats: certainCar_seats,
      seat: this.data.seat,
      value: [0,this.data.seat-1],
      isFixed: true
    })
  },
  //我要乘车
  takeBus(){
    
    if (!distanceArray||distanceArray.length == 0){
      wx.showToast({
        title: '环校车也要休息哦~',
        icon: 'none'
      })
      return
    }
    if(this.data.isFirst){
      wx.showModal({
        title: '提示',
        content: "请先乘坐上环校车，再按实际车号与座位号进行支付。请勿提前支付！",
        showCancel: false
      })
      this.setData({isFirst: false})
    }
    seats = []
    cars = []
    var _car = distanceArray[0].carId
    for(var i in distanceArray){
      var id = distanceArray[i].carId
      cars.push(id)
      // if (id < 10){
      //   cars.push("0" + id)
      //   distanceArray[i].carId = "0" + id
      // }else{                              
      //   cars.push(id)
      // }
      // else if(id> 14){
      //   cars.push(id + 1)
      // }
    }
    totalSeats = distanceArray[0].tolalNumber      //第一辆车的总座位数
    distanceArray.forEach(item =>{
      if (item.carId == this.data.car){
        totalSeats = item.tolalNumber
      }
    })
    for (let i = 1; i <= totalSeats; i++) {
      if (i < 10) {
        i = "0" + i;
      }
      seats.push(i)
    }
    if (this.data.car !=" ") {
      _car = this.data.car
    }
    this.setData({
      isFixed: true,
      cars: cars,
      seats: seats,
      car: _car,
    })
    distanceArray.forEach((item,index) => {
      if (item.carId == _car) {
        this.setData({
          value: [index, this.data.seat - 1],
        })
      }
    })
    // distanceArray.forEach(item => {
    //   if (item.carId == this.data.car) {
    //     totalSeats = item.tolalNumber
    //   }
    // })
    // if (this.data.car != '') {
    //   _car = this.data.car
    //   console.log(_car)
    //   if (_car == id) {
    //     console.log(i, this.data.seat - 1)
        
    //     console.log(this.data.value)
    //   }
    // }
    // this.setData({
    //   car: ,
    //   seat: 
    // })
    itemChoose = false
  },
  showMessage(){
    var seat = parseInt(this.data.seat)
    wx.showModal({
      title: '已支付',
      content: this.data.payedCar + '号车,' + this.data.payedSeat + '号座',
      showCancel: false
    })
  },
  stopSwiper(){
    return false
  },
  // beforeBook(e){
  //   if (distanceArray.length == 0) {
  //     wx.showToast({
  //       title: '环校车也要休息哦~',
  //       icon: 'none'
  //     })
  //     return
  //   }
  //   this.setData({
  //     isBookFixed: true
  //   })
  // },
  // // 查看预约状态
  // checkBook(){
  //   this.setData({
  //     checkBook: true
  //   })
  // },
  // // 取消预约
  // cancelBook(){
  //   wx.showModal({
  //     title: '提示',
  //     content: '确定取消预约？',
  //     success:res =>{
  //       if (res.confirm) {
  //         wx.showLoading({
  //           title: '请求中...',
  //         })
  //         wx.request({
  //           url: globalUrl + 'passenger/cancelReservation',
  //           header: app.globalData.header,
  //           method: 'POST',
  //           success: res =>{
  //             wx.hideLoading()
  //             if(res.data.serviceResult == "1"){
  //               this.setData({
  //                 isBook: false,
  //                 isBookFixed: false,
  //                 checkBook: false
  //               })
  //               wx.showToast({
  //                 title: '已取消'
  //               })
  //             }else{
  //               wx.showToast({
  //                 title: '错误',
  //                 icon: 'none'
  //               })
  //             }
  //           }
  //         })
          
  //       }
  //     }
  //   })
  // },
  // bindChange_book(e){
  //     const val = e.detail.value
  //     this.setData({
  //       store: this.data.stores[val[0]],
  //       can: true
  //     })
  // },
  // bindpickstart_book(e){
  //   this.setData({can: false})
  // },
  // bindpickend_book(e){
  //   this.setData({can: true})
  // },
  // sureBook(){
  //   if(!this.data.can)
  //     return
  //   //发送预约请求、
  //   wx.request({
  //     url: globalUrl + 'passenger/reservation?position=' + this.data.store,
  //     header: app.globalData.header,
  //     method: 'GET',
  //     success: res => {
  //       if (res.data.serviceResult == "1"){
  //         this.setData({
  //           isBook: true,
  //           isBookFixed: false,
  //         })
  //         wx.showToast()
  //         setTimeout(()=>{
  //           this.setData({
  //             isBook: false
  //           })
  //         },15*60*1000)
  //       }
  //     }
  //   })
  // },
  //包车
  showcontext(){
    wx.showModal({
      title: '说明',
      content: '包车业务请致电环校车办公室13553577628',
      confirmText: '拨号',
      success: res=> {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: '13553577628' // 仅为示例，并非真实的电话号码
          })
        }
      }
    })
  },
  //首页滑动
  swiperChange(e){
    this.setData({ current: e.detail.current} )
  },
  next(){
    var tips = this.data.tips
    if(tips == 4){
      this.setData({isFirst: false})
      return
    }
    tips++
    this.setData({
      tips
    })
  },
  onShareAppMessage: function () {
    return {
      title: "环校车来啦，赶紧上车！",
      path: 'pages/index/index',
      success(res) {
      }
    }
  }
})

